package list;

public class MyArrayList<T> implements MyList<T> {
    private Object[] arr = new Object[2];
    private int size = 0;

    @Override
    public boolean add(T date) {
        //扩容
        arr[size] = date;
        size++;
        if (size == arr.length) {
            Object[] temp = new Object[arr.length * 2];
            for (int i = 0; i < size; i++) {
                temp[i] = arr[i];
            }
            arr = temp;//改变指向
        }
        return true;
    }

    @Override
    public boolean add(int index, T date) {
        //索引不在范围怎么办？比如-1
        checkPostionIndex(index);
        //空间不够怎么办？
        if (size == arr.length) {
            Object[] temp = new Object[arr.length * 2];
            for (int i = 0; i < size; i++) {
                temp[i] = arr[i];
            }
            arr = temp;//改变指向
        }
        //如何插入一个元素
        for (int i = size; i > index; i--) {
            arr[i] = arr[i - 1];
        }
        arr[index] = date;
        size++;
        return true;
    }

    @Override
    public T remove(T date) {
        T oldDate = null;
        for (int i = 0; i < size; i++) {
            if (date == arr[i] || date.equals(arr[i])) {
                oldDate = (T) arr[i];
                for (int j = 0; j < size - 1; j++) {
                    arr[j] = arr[j + 1];
                }
                break;
            }
        }
        size--;
        return oldDate;
    }

    @Override
    public T remove(int index) {
        checkElementIndex(index);
        return null;
    }

    @Override
    public boolean set(int index, T date) {
        checkElementIndex(index);
        arr[index] = date;
        return true;
    }

    @Override
    public T getValue(int index) {
        checkElementIndex(index);
        return (T) arr[index];
    }

    @Override
    public int size() {
        return size;
    }

    private void checkElementIndex(int index) {
        if (index < 0 || index >= size) {
            throw new RuntimeException("取元素的索引越界");
        }
    }

    private void checkPostionIndex(int index) {
        if (index < 0 || index > size) {
            throw new RuntimeException("索引越界");
        }
    }
}
